//
//  AddCarYearCheckVC.m
//  ZuLinProject
//
//  Created by bancheng on 2021/12/27.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXYearCheckApplyViewController.h"
#import "LXTableViewCell.h"
#import "LXYearCheckModel.h"
#import "LXRemarkTabelViewCell.h"
#import "LXChooseManagerViewController.h"
#import "LXChooseCarViewViewController.h"
#import "FuZeRenModel.h"
#import "LXApplyAnnexTableCell.h"

@interface LXYearCheckApplyViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *data;
@property (nonatomic) NSMutableDictionary *loanDic;
@property (nonatomic) NSDictionary *selDic;
@property (nonatomic) CheLiangModel *carModel; // 车辆数据
@property (nonatomic) NSString *inviteId; // 负责人id
@property (nonatomic) FuZeRenModel *fuZeModel; //  负责人模型

@property (nonatomic) NSMutableArray *annexAry;
@property (nonatomic) NSMutableArray *annexDataAry;

@end

@implementation LXYearCheckApplyViewController



- (void)viewDidLoad {
    [super viewDidLoad];

    
    if (self.type==1) {
       
        [self layoutCustomNav:self.view title:@"新增年检"];
    }
    else {
        
        [self layoutCustomNav:self.view title:@"修改年检信息"];
    }
    
    
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[LXTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXTableViewCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRemarkTabelViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
    [self.tableView registerClass:[LXApplyAnnexTableCell class] forCellReuseIdentifier:NSStringFromClass([LXApplyAnnexTableCell class])];

    NSDictionary *dic = @{
        @"url":@"upLoad_B",
    };
    self.annexAry = [NSMutableArray array];
    self.annexDataAry = [NSMutableArray array];
    [self.annexAry addObject:dic];
    
    

    [self loadData];
    
    if (self.type==1) {
        [self setBottomViewWithText:@"确认新增"];
    }
    else {
        [self setBottomViewWithText:@"确认修改"];
    }
    

}

- (void)loadData{
    
    self.loanDic  = [NSMutableDictionary dictionary];
    
    
    // 模型不为空,说明从车辆详情进入
    if (!ObjectIsEmpty(self.yearCheckModel)) {

        // 车牌号
        [self.loanDic setValue:self.yearCheckModel.carNum forKey:@"carNum"];
        self.carModel = [CheLiangModel new];
        self.carModel.ID = self.yearCheckModel.carId;
        self.carModel.carNum = self.yearCheckModel.carNum;
        
        // 修改的时候需要带入数据
        if (self.type==2) {

            // 负责人
            self.inviteId = self.yearCheckModel.inviteId;
            [self.loanDic setValue:self.yearCheckModel.chargeName forKey:@"chargeName"];
            
            self.fuZeModel = [FuZeRenModel new];
            self.fuZeModel.ID = self.inviteId;
            self.fuZeModel.realName = self.self.yearCheckModel.chargeName;
            
            // 当前年检时间
            [self.loanDic setValue:self.yearCheckModel.currentInspectTime forKey:@"currentInspectTime"];
            [self.loanDic setValue:self.yearCheckModel.nextInspectTime forKey:@"nextInspectTime"];
            
            // 应付日期
            [self.loanDic setValue:self.yearCheckModel.expectPayDate forKey:@"expectPayDate"];
            // 应付金额
            [self.loanDic setValue:self.yearCheckModel.amount forKey:@"amount"];
            // 备注
            [self.loanDic setValue:self.yearCheckModel.remark forKey:@"remark"];

            
            //图片
            for (NSString *url in self.yearCheckModel.pics) {
                NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HTTP_URL,url];
                [self.annexAry insertObject:@{@"url":imageUrl} atIndex:0];
                [self.annexDataAry insertObject:url atIndex:0];
            }
            
        }

    }
    
    
   
    
    
    
    self.data = @[
        
        @{
            @"title":ObjectIsEmpty(self.yearCheckModel)?@"*车牌号":@"车牌号",
            @"key":@"carNum",
            @"placeHolder" : @"请选择车牌号",
            @"canEdit":@(NO),
            @"showAccess":ObjectIsEmpty(self.yearCheckModel)?@(YES):@(NO),
            @"maxLength":@(1000),
            @"sel":ObjectIsEmpty(self.yearCheckModel)?@"clickCarNum":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":self.type==1?@"*负责人":@"负责人",
            @"key":@"chargeName",
            @"placeHolder" : @"请选择负责人",
            @"canEdit":@(NO),
            @"showAccess":self.type==1?@(YES):@(NO),
            @"maxLength":@(1000),
            @"sel":self.type==1?@"clickManager":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":self.type==1?@"*本次年检日期":@"本次年检日期",
            @"key":@"currentInspectTime",
            @"placeHolder" : @"请选择本次年检日期",
            @"canEdit":@(NO),
            @"showAccess":self.type==1?@(YES):@(NO),
            @"maxLength":@(1000),
            @"sel":self.type==1?@"clickCurrentInspectTime":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":self.type==1?@"*应付年检金额(元)":@"应付年检金额(元)",
            @"key":@"amount",
            @"placeHolder" : @"请输入年检金额",
            @"canEdit":self.type==1?@(YES):@(NO),
            @"keyboardType":@(UIKeyboardTypeDecimalPad),
            @"maxLength":@(8),
            @"showAccess":@(NO),
            @"sel":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":self.type==1?@"*应付日期":@"应付日期",
            @"key":@"expectPayDate",
            @"placeHolder" : @"请选择应付日期",
            @"canEdit":@(NO),
            @"showAccess":self.type==1?@(YES):@(NO),
            @"maxLength":@(1000),
            @"sel":self.type==1?@"clickExpectPayDateAction":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":self.type==1?@"*年检到期日期":@"年检到期日期",
            @"key":@"nextInspectTime",
            @"placeHolder" : @"请选择年检到期日期",
            @"canEdit":@(NO),
            @"showAccess":self.type==1?@(YES):@(NO),
            @"maxLength":@(1000),
            @"sel":self.type==1?@"clickNextInspectTime":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"年检照片(最多4张)",
            @"key":@"annex",
            @"height":@(kComAnnexHeight)
        },
        @{
            @"title":@"备注",
            @"key":@"remark",
            @"height":@(150)
        },

       
 ].mutableCopy;
    
    
   
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.data[indexPath.row];
    if ([dic[@"key"] isEqualToString:@"annex"]) {
        return [LXApplyAnnexTableCell getCellHeightWithDataSource:self.annexAry] + 30;
    }
    return [dic[@"height"] doubleValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = self.data[indexPath.row];

    //
    if([dic[@"key"]  isEqualToString:@"annex"]){
        
        LXApplyAnnexTableCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXApplyAnnexTableCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.titleLab.text = dic[@"title"];
        
        [cell reloadAnnexData:self.annexAry WithMaxNum:4];
        

        // 添加图片
        [cell setCallBackTakeAnnex:^(NSInteger num) {
            
            [self.view endEditing:YES];
            [[LXPhotoHelper shareHelper] showImageViewSelcteWithResultBlock:^(id data) {
                
                [self uploadImage:data];
                
            } andMultipleImageBlock:^(id data) {
                
                [self uploadImage:data];
                
            } andSelectedNum:4 - self.annexDataAry.count];
            
        }];
        
        
        // 放大图片
        [cell setCallBackExtendAnnex:^(NSInteger num,id obj) {
            [self.view endEditing:YES];
            LXBigImageView *view = [[LXBigImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) WithShowImageAry:self.annexDataAry];
            [view.scrollView setContentOffset:CGPointMake(ScreenWidth*num, 0) animated:NO];
            [[UIApplication sharedApplication].delegate.window addSubview:view];
            
        }];
        // 删除图片
        [cell setCallBackDeleteAnnex:^(NSInteger num) {
            [self.view endEditing:YES];
            [self.annexAry removeObjectAtIndex:num];
            [self.annexDataAry removeObjectAtIndex:num];
            [self.tableView reloadData];
        }];
        

        return cell;
        
    }
    
    // 备注
    if([dic[@"key"]  isEqualToString:@"remark"]){
       LXRemarkTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
       cell.selectionStyle = UITableViewCellSelectionStyleNone;
       [cell setClipsToBounds:YES];
       cell.textView.placeholder = @"请输入 ~";
       cell.textView.maxLength = 200;
       cell.remarkTitle.text = dic[@"title"];
       cell.textView.text = self.loanDic[dic[@"key"]];
       [cell setTextViewEdit:^(NSString * _Nonnull textStr) {
           self.loanDic[dic[@"key"]]  = textStr;
       }];
       return cell;
   }
    
    LXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setClipsToBounds:YES];
    

    cell.cellDic = dic;
    cell.textFiled.hidden = NO;
    cell.subTitleLab.hidden = YES;
    cell.textFiled.text = self.loanDic[dic[@"key"]];
    
    
    cell.textfiledChangeBlock = ^(NSString * _Nonnull textStr) {
        self.loanDic[dic[@"key"]]  = textStr;
    };
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = self.data[indexPath.row];
    self.selDic = dic;
    NSString * selName = dic[@"sel"];
    SEL action = NSSelectorFromString(selName);
    if ([self respondsToSelector:action]) {
        [self performSelector:action withObject:nil afterDelay:0];
    }

}

#pragma mark -- 选择当前年检时间
-(void)clickCurrentInspectTime{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"currentInspectTime"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择当前年检日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        [weakSelf.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
        [weakSelf.tableView reloadData];
    };
}
#pragma mark -- 选择下次年检时间
-(void)clickNextInspectTime{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"nextInspectTime"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择年检到期日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        if([NSString compareDate:self.loanDic[@"currentInspectTime"] withDate:yearString withFormat:@"yyyy-MM-dd"]==-1){
            showAlert(@"下次年检日期不能小于本次年检日期");
        }
        else {
            [weakSelf.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
            [weakSelf.tableView reloadData];
            
        }
    };
}


#pragma mark -- 选择应付时间
-(void)clickExpectPayDateAction{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"expectPayDate"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择应付日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        
//        if([NSString compareDate:self.loanDic[@"expectPayDate"] withDate:yearString withFormat:@"yyyy-MM-dd"]==-1){
//            showAlert(@"应付日期不能小于本次年检日期");
//        }
//        else {
            [weakSelf.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
            [weakSelf.tableView reloadData];
            
//        }
        
    };
}

#pragma mark -- 选择负责人
-(void)clickManager{
    [self.view endEditing:YES];
    
    LXChooseManagerViewController *vc = [[LXChooseManagerViewController alloc] init];
    WEAKSELF
    [vc setToSendValue:^(FuZeRenModel * _Nonnull model) {
        [weakSelf.loanDic setValue:model.realName forKey:@"chargeName"];
        weakSelf.inviteId = model.ID;
        weakSelf.fuZeModel = model;
        [weakSelf.tableView reloadData];
    }];
    vc.model = self.fuZeModel;
    [self pushToNextController:vc];
}



#pragma mark -- 选择车牌号
- (void)clickCarNum{
    
    LXChooseCarViewViewController *vc = [[LXChooseCarViewViewController alloc] init];
    vc.type = @"12";
    vc.comfrom = 1;
    [vc setToSendValue:^(CheLiangModel * _Nonnull model) {
        self.carModel = model;
        [self.loanDic setValue:model.carNum forKey:self.selDic[@"key"]];
        [self.tableView reloadData];
        
    }];
    [self pushToNextController:vc];
}


- (NSMutableArray *)data{
    if (!_data) {
        _data = [[NSMutableArray alloc]init];
    }
    return _data;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, ScreenHeight - kViewTopHeight - kComHeight - 5) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}


#pragma mark ---- 确认新增/修改点击事件
- (void)clickBottomView:(UIButton *)sender{
    
   
    if (StringIsEmpty(self.loanDic[@"carNum"])) {
        showAlert(@"请选择车牌号");
        return;
    }
    
    if (StringIsEmpty(self.loanDic[@"chargeName"])) {
        showAlert(@"请选择负责人");
        return;
    }
    
    if (StringIsEmpty(self.loanDic[@"currentInspectTime"])) {
        showAlert(@"请选择本次年检日期");
        return;
    }
    
    if (StringIsEmpty(self.loanDic[@"amount"])) {
        showAlert(@"请输入年检金额");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"expectPayDate"])) {
        showAlert(@"请选择应付日期");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"nextInspectTime"])) {
        showAlert(@"请选择年检到期日期");
        return;
    }
    

    
    NSMutableDictionary *dic = @{
        
        @"carId":self.carModel.ID, // 所属车辆id
        @"carNum":self.carModel.carNum,// 所属车辆车牌号
        @"chargeName":self.loanDic[@"chargeName"],// 负责人
        @"inviteId":self.inviteId,// 负责人id
        @"currentInspectTime":self.loanDic[@"currentInspectTime"],//  当前年检日期
        @"nextInspectTime":self.loanDic[@"nextInspectTime"],//  年检到期日期
        @"amount":self.loanDic[@"amount"], //  应付金额
        @"expectPayDate":self.loanDic[@"expectPayDate"], //  应付日期
        @"remark":self.loanDic[@"remark"], //  备注
        @"pics":self.annexDataAry
        
    }.mutableCopy;
    
    NSString *url;
    // 新增维修
    if (self.type==1) {
        url = [NSString stringWithFormat:@"%@",TyearlyinspectionAdd_URL];
    }
    // 修改维修的时候需要穿id
    else if (self.type==2) {
        url = [NSString stringWithFormat:@"%@",TyearlyinspectionUpdate_URL];
        [dic setValue:self.yearCheckModel.yearlyInspectionId forKey:@"yearlyInspectionId"];
    }

    
    [Tool showAlertTitle:@"是否确认提交" msg:nil cancelTitle:@"取消" commitBtnTitle:@"确定" cancelHandlerBlock:^{
    } commitHandlerBlock:^{
        [MSNetworkManager postRevertUrl:url params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            
            
            if (isSuccess) {
                
                if (self.type==1) {
                    showAlert(@"新增年检成功");
                }
                else {
                    showAlert(@"修改年检成功");
                }
                
                
                // carModel 有值说明从详情页进入,返回时须刷新列表
                if (!ObjectIsEmpty(self.yearCheckModel)) {
                    kUserDefaultSetBool(YES, kRefreshStr);
                }
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
        } withShowHud:YES];
    } onVC:self];
    
   
}


-(void)uploadImage:(NSArray *)ary{
    
    [self.annexAry removeLastObject];
    MBProgressHUD *hud = [MBProgressHUD showGif];
        
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
    dispatch_async(queue, ^{
    
    [ary enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    
        [MSNetworkManager postRevertUrl:POST_UploadFile_URL params:@{@"type":@"1"} formData:@[obj] success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            if (isSuccess) {
                
                NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HTTP_URL,resonseObj[@"url"]];
                [self.annexAry addObject:@{
                    @"url":imageUrl
                }];
                [self.annexDataAry addObject:resonseObj[@"url"]];
                
                if (idx == ary.count-1) {
                    [hud hide];
                    [self.annexAry addObject:@{
                        @"url":@"upLoad_B",
                    }];
                   
                    [self.tableView reloadData];
                }
                dispatch_semaphore_signal(semaphore);
            }
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
            dispatch_semaphore_signal(semaphore);
            [hud hide];
        } withShowHud:NO];
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        
     }];
    });

}


@end
